package com.jrx.anytxn.customer.listener;

import com.jrx.anytxn.common.uitl.JsonUtils;
import com.jrx.anytxn.customer.bean.CreditApprovalBean;
import com.jrx.anytxn.customer.service.ICustomerLimitInfoService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

@Service
@RocketMQTransactionListener
public class InvestorCreditMqTransactionListener implements RocketMQLocalTransactionListener {

    private static final Logger logger = LoggerFactory.getLogger(InvestorCreditMqTransactionListener.class);

    @Autowired
    private ICustomerLimitInfoService iCmCustomerLimitInfoService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {

        try {
            /*
             * 目前这边事务MQ只有一处地方，所以此处没有做任何处理
             * 之后多处使用到事务MQ时，此处需要做判断，在参数中加入用于判断参数
             * 在下面代码中通过判断参数中的值，做相应的处理
             */
            logger.debug("联合贷授信MQ发送端获取到的写表数据 ：{}", JsonUtils.toJSon(arg));
            CreditApprovalBean bean = (CreditApprovalBean) arg;
            iCmCustomerLimitInfoService.registerCustomerLimitInfo(bean);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            logger.error("联合贷授信MQ发送端写数据异常：{}", e);
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        // ... check transaction status and return bollback, commit or unknown
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
